// pages/start.js
const QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
let qqmapsdk;

const Login = require('login.js').loginFunc;
const RequestToken = require('login.js').requestToken;
const LoginWithPhone = require('login.js').LoginWithPhone;
// const AuthPhone = require('auth.js').AuthPhone;
const getUserStudyInfo = require('login.js').getUserStudyInfo;
// const cityList = require('../../lib/city.js');
const area = require("../../lib/city.js").areaList;
const loadStudy = require('loadStudy.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    welcome: null,
    welcomeWrod: '你好，欢迎',
  },

  /**
   * 流程首先wxlogin，之后如果无记录token则跳到手机登录授权页面
   */
  onLoad: function (options) {
    // 登录
    Login()
      .then(d => { // 微信登陆获取code
        return d.code;
      })
      .then(wxcode => { // 请求服务器token
        return RequestToken(wxcode)
      })
      .then(d => { // 判断有没有token的存在
        let res = d.res.data.data;
        if (res.token) { // 返回数据有token则登陆成功
          getApp().globalData.login = {
            openId: res.openId,
            sessionKey: res.sessionKey,
            wxCode: d.wxcode,
            token: res.token,
          }
          if(res.userInfo){
            getApp().globalData.userInfo = res.userInfo;
          }
          this.getUserInfo();
        } else { // 没有token去拿手机号码绑定token
          getApp().globalData.login = {
            openId: res.openId,
            sessionKey: res.sessionKey,
            wxCode: d.wxcode,
            token: res.token,
          }
          if (res.userInfo) {
            getApp().globalData.userInfo = res.userInfo;
          }
          return this.showPage('authPhone');
        }
      })
      .catch(err => {
        console.warn(JSON.stringify(err));
        wx.showModal({
          title: '错误',
          content: '服务暂时不可用，请稍后重试',
          showCancel: false,    
          success()  {
            wx.reLaunch({
              url: 'start',            
            })
          }
        })
      })
  },
  onReady: function () {
  },
  getUserLocationAndJump: function (wxUserInfo) {
    // 更新用户的微信信息,假如没有则更新
    if (!wxUserInfo.gender || !wxUserInfo.nickName || !wxUserInfo.avatarUrl){
      getUserStudyInfo(getApp().globalData.login.token,wxUserInfo)
      .then( d => {
        // 第一次，把设置服务器用户信息保存到全局;
        getApp().globalData.userInfo = d.data.data;
      })
      .catch( e => {
        console.warn(e);
      });
    }
    // 获取用户的学习信息
    loadStudy();
    //
    //// 腾讯地图实例
    

  },
  getUserInfo: function () { // 获取基本用户信息
    console.log('globaldata info',getApp().globalData)
    wx.getSetting({
      success: (res) =>{
        // console.log(res);
        if (res.authSetting['scope.userInfo']){
          wx.getUserInfo({
            withCredentials: false,
            lang: 'zh_CN',
            success: (res) =>{
              getApp().globalData.userWxInfo = res.userInfo;
              this.getUserLocationAndJump(res.userInfo);
            },
            fail: function(res) {
              wx.showModal({
                title: '错误',
                content: '获取用户信息权限验证失败',
                showCancel: false,
                confirmText: '知道了',
                confirmColor: '',
              })
            },
            complete: function(res) {},
          })
        }else{
          this.showPage('authuInfo');
        }
      },
      fail: function(res) {
        wx.showModal({
          title: '错误',
          content: '获取用户信息权限验证失败',
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '', 
        })
      },
      complete: function(res) {},
    })
  },
  getUInfo:function(e){
    console.log(e);
    getApp().globalData.userWxInfo = e.detail.userInfo;
    /// 地图定位功能并进入首页
    this.getUserLocationAndJump(e.detail.userInfo);
  },
  failToLocateCity: function (e) {  // 不能进入站点页面
    console.warn(e);
    wx.navigateTo({ // 跳转选择站点
      url: '../citySelect/citySelect?location=fail',
    })
  },
  showPage:function(name){
    switch(name){
      case 'authPhone':
        this.setData({
          welcome: 'authPhone',
          needback:true,
        })
      break;
      case 'authuInfo':
        this.setData({
          welcome: 'authuInfo',
          needback:true,
        })
      break;
      default:
        this.setData({
          welcome:null,
        })
    }
    return false;
  },
  getPhone:function(e){ // 获取手机授权
    if (e.detail.errMsg && e.detail.errMsg === "getPhoneNumber:ok"){
      LoginWithPhone(e.detail)
      .then( d => {
        this.getUserInfo(); // 获取用户信息
      })
      .catch( e => {
        console.warn(e);
      })
    }
  },
  closeApp:function(){
    wx.navigateBack({
      delta: -1,
    })
  }
})